<template>
  <div class="product-detail-container">
    <el-page-header @back="goBack" title="返回">
      <template #content>
        <span class="page-title">商品详情</span>
      </template>
    </el-page-header>

    <el-card v-loading="loading" class="detail-card" style="margin-top: 20px;">
      <template v-if="!loading && product">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="商品ID">
            {{ product.productId }}
          </el-descriptions-item>
          <el-descriptions-item label="商品名称">
            {{ product.productName }}
          </el-descriptions-item>
          <el-descriptions-item label="价格">
            <span style="color: #f56c6c; font-weight: bold; font-size: 18px;">¥{{ product.price }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="新旧程度">
            <el-tag>{{ product.oldLevel }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(product.status)">
              {{ getStatusText(product.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="卖家ID">
            {{ product.userId }}
          </el-descriptions-item>
          <el-descriptions-item label="发布时间">
            {{ formatDateTime(product.creatTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(product.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="商品描述" :span="2">
            {{ product.productDetail || product.description || '暂无描述' }}
          </el-descriptions-item>
          <el-descriptions-item label="商品图片" :span="2">
            <div class="image-gallery">
              <template v-if="productImages.length > 0">
                <el-image
                  v-for="(img, index) in productImages"
                  :key="index"
                  :src="img"
                  :preview-src-list="productImages"
                  :initial-index="index"
                  fit="cover"
                  class="product-image"
                  lazy
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                  <template #placeholder>
                    <div class="image-loading">加载中...</div>
                  </template>
                </el-image>
              </template>
              <div v-else class="no-image">
                <el-icon><Picture /></el-icon>
                <p>暂无商品图片</p>
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </template>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const product = ref(null)

const productId = computed(() => route.params.id)

const productImages = computed(() => {
  if (!product.value) return []
  
  // 尝试多种可能的图片字段（后端实际字段是coverList）
  const imageData = product.value.coverList || product.value.images || product.value.image || product.value.productImages || product.value.img
  
  if (!imageData) {
    console.log('❌ 商品ID', product.value.productId, '没有图片字段')
    return []
  }
  
  console.log('🔍 商品ID', product.value.productId, 'coverList原始数据:', imageData, '类型:', typeof imageData)
  
  // 如果已经是数组，直接返回
  if (Array.isArray(imageData)) {
    console.log('✅ 已是数组，图片数量:', imageData.length)
    return imageData.filter(url => url && url.trim()) // 过滤空值
  }
  
  // 如果是字符串，尝试多种解析方式
  if (typeof imageData === 'string') {
    const trimmed = imageData.trim()
    
    // 空字符串
    if (!trimmed) {
      console.log('❌ 空字符串')
      return []
    }
    
    // 尝试解析为JSON数组
    if (trimmed.startsWith('[')) {
      try {
        const parsed = JSON.parse(trimmed)
        if (Array.isArray(parsed)) {
          console.log('✅ JSON数组解析成功，图片数量:', parsed.length)
          return parsed.filter(url => url && url.trim())
        }
      } catch (e) {
        console.log('❌ JSON数组解析失败:', e.message)
      }
    }
    
    // 尝试按逗号分隔（可能是逗号分隔的URL列表）
    if (trimmed.includes(',')) {
      const urls = trimmed.split(',').map(url => url.trim()).filter(url => url)
      if (urls.length > 0) {
        console.log('✅ 逗号分隔解析成功，图片数量:', urls.length)
        return urls
      }
    }
    
    // 单个URL
    console.log('✅ 作为单个URL处理')
    return [trimmed]
  }
  
  console.log('❌ 未知数据类型')
  return []
})

const getStatusType = (status) => {
  const types = {
    available: 'success',
    sold: 'info',
    reserved: 'warning',
    removed: 'danger'
  }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = {
    available: '在售',
    sold: '已售',
    reserved: '预定',
    removed: '下架'
  }
  return texts[status] || status
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  
  try {
    const date = new Date(dateTime)
    
    // 检查是否是有效日期
    if (isNaN(date.getTime())) {
      return dateTime
    }
    
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch {
    return dateTime
  }
}

const getProductDetail = async () => {
  loading.value = true
  try {
    const response = await request.get(`/admin/product/detail/${productId.value}`)
    if (response.code === 0) {
      product.value = response.data
    } else {
      ElMessage.error(response.message || '获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.back()
}

onMounted(() => {
  getProductDetail()
})
</script>

<style scoped>
.product-detail-container {
  padding: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
}

.detail-card {
  border-radius: 8px;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s;
}

.product-image:hover {
  transform: scale(1.05);
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.image-error .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background: #f5f7fa;
  border-radius: 8px;
  color: #909399;
  font-size: 14px;
}

.no-image .el-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.no-image p {
  margin: 0;
}

.image-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #f0f0f0;
  color: #909399;
  font-size: 12px;
}
</style>
